<?php

namespace App\Http\Controllers\Admin;

use App\GroupBuy;
use App\GroupMaster;
use App\Http\Controllers\Controller;
use App\Http\Response;
use Illuminate\Http\Request;

class GroupBuyController extends Controller
{
    use Response;

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
       $result=GroupBuy::with('goods')->latest()->paginate($request->get('pageSize'),'*','pageNo');
       return $this->success(200,$result);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $result=GroupBuy::find($id);
        return $this->success(200,$result);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        GroupBuy::create($request->all());
        return $this->message(200,'创建成功');
    }

    /**
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($id, Request $request)
    {
        $update=GroupBuy::where('id',$id)->update($request->all());
        if ($update){
            return $this->message(200,'更新成功');
        }else{
            return $this->error(505,'更新失败');
        }
    }

    public function destroy($id)
    {
        $find=GroupMaster::where('group_buy_id',$id)->count();

        if ($find>0){
          return  $this->error(505,'有人在拼团,删除失败');
        }

        $delete=GroupBuy::destroy($id);
        if ($delete){
            return $this->message(200,'删除成功');
        }else{
            return $this->error(505,'删除失败');
        }

    }

}
